Lambda Expressions

Lambdas are anonymous functions. They are functions that can be made on the fly, and are used to for a variety of purposes. They could be used as a key for a sorting algorithm, or as a quick way to delegate items in some fashion. In this lecture we will cover:

1. Initialzing a Lambda Expression
2. Rewriting normal functions as lambda expressions
3. Using lambda expressions in other contexts

Let's go over examples of lambda expressions, from creating them to using them in time-saving manners.

Initializing a Lambda Expression

Before beginning to explain this lambda expressions workings, it is important to understand that the following lambda expression is actually no use to us. This is because lambda expressions need labels to be used. These labels can be assigned when assigning the expression to a variable.


In [1]:
lambda x,y : x%y


Out[1]:
<function __main__.<lambda>>

In [2]:
length_func = lambda x: len(x)

In [3]:
length_func("hello, there!")


Out[3]:
13

As seen, when we assign a lambda expression to a label we can use it. Note that at default lambda expressions return the expected type of whatever it is handling. If you send in a number and do a numerical operation, you will receive back a number, a string a string, etc.

Below, we want to create more complex lambda expressions. How would we return True or False if a number was even or odd, respectively? How about first getting the what result of mod 2 is?


In [5]:
# Even or Odd lambda
even_odd = lambda x: x % 2 == 0

As we can see, the lambda expressions returns the number we expected. How do we return a True or False value? Note: we can't use if statements or returns. This limits the power of the lambda. However, we can have lambda expressions return True or False, still. Observe the following syntax.


In [6]:
even_odd = lambda x: True if x % 2 == 0 else False

In [28]:
even_odd(9)


Out[28]:
False

Soon, we will learn about creating our own classes, and eventually data structures. When we learn how to make our own data structures, we'll rewrite what are "conventionally" (take it lightly) known as a "magic methods". These methods are not called upon explicitly, but are triggered by some internal action that Python sees you carried out. For example the + in Python triggers the magic method:

__add__()

We are going to create data structures that can be printed out. When you print out a list you get the following output:

[obj1, obj2, ...., objn]

However, this favorable stringification is something we have to build for our own data structures. So, how would be implement it? Well, we would rewrite what is known as the

__str__()

function. This is the equivalent to toString() if you are familiar with Java. We will generate a bunch of numbers from a data structure that is arbitrary to us right now (lets just use a tuple), and try to get it into looking like a list. We'll use a lambda expression because we can perform the action ad-hoc, and act as a temporary str() method, for a pretend list.


In [9]:
# script that "converts" a tuple to a list
some_tup = ("[", 3, 4, "hello", "]")
x = lambda tup: ", ".join(str(item) for item in tup)
print(x(some_tup))


[, 3, 4, hello, ]

Somewhat scrappy, but let's just say it's pretty close to looking like an actual list. Strings are not mutable so we can't just add a bracket at the beginning or right at the end. There are certain ways to make this possible, however. Operations like this are better suited for functions, anyways.

Lambdas as Parameters

We have a function known as sorted(). This function accepts an iterable, and a key (and reverse, talked below). The iterable alone acts as expected.


In [10]:
sorted([4, 2, 8, 5, 2, 9])


Out[10]:
[2, 2, 4, 5, 8, 9]

However, we have much more power with the key. The key accepts a form of some type of filter. We can send in a lambda expression to change what sorted means to us. What if we wanted the even numbers to be at the end?


In [27]:
sorted([4, 2, 8, 5, 2, 9], key=lambda x: x%2 == 0)


Out[27]:
[5, 9, 4, 2, 8, 2]

What if we wanted the numbers to be reversed, such as in descending order?


In [28]:
sorted([1, 5, 2, 5, 2, 9, 4], reverse=True)


Out[28]:
[9, 5, 5, 4, 2, 2, 1]

In [29]:
lst = [1, 3, 4,5]

In [31]:
lst[::-1]


Out[31]:
[5, 4, 3, 1]